package com.jlboot.core.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JsonNode;
import com.jfinal.core.Controller;
import com.jlboot.core.exception.JlServerException;
import io.swagger.v3.core.util.Yaml;
import io.swagger.v3.jaxrs2.Reader;
import io.swagger.v3.oas.models.OpenAPI;
import org.reflections.Reflections;
import org.reflections.util.ConfigurationBuilder;

import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author wangsanfei
 * @version 1.0
 * Create by 2024/3/13 19:10
 */
public class OpenApiUtil {

    public static String createYaml(String packageName){

        Reflections reflections = new Reflections(new ConfigurationBuilder().forPackages(packageName));
        Set typeClass = reflections.getSubTypesOf(Controller.class);


        Reader reader = new Reader(new OpenAPI());
        OpenAPI openAPI = reader.read((Set<Class<?>>) typeClass);

        try {
            Yaml.mapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
            // parse JSON
            JsonNode jsonNodeTree = Yaml.mapper().readTree(Yaml.mapper().writeValueAsString(openAPI));
            // return it as YAML
            String yaml= Yaml.mapper().writeValueAsString(jsonNodeTree);
            return yaml;
        } catch (Exception e) {
            e.printStackTrace();
            throw new JlServerException("生成API错误",e);
        }

    }

    /**
     * TODO
     * @param packageName
     * @return
     */
    public static String createJson(String packageName){

        Reflections reflections = new Reflections(new ConfigurationBuilder().forPackages(packageName));
        Set typeClass = reflections.getSubTypesOf(Controller.class);

        Reader reader = new Reader(new OpenAPI());
        OpenAPI openAPI = reader.read((Set<Class<?>>) typeClass);

        try {
            Yaml.mapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
            // parse JSON
            JsonNode jsonNodeTree = Yaml.mapper().readTree(Yaml.mapper().writeValueAsString(openAPI));
            return jsonNodeTree.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new JlServerException("生成API错误",e);
        }

    }

}
